<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use app\common\traits\SelectPage;
use think\Model;
use think\db;

/**
 * Class CourseNormal
 * 常规课
 */

class CourseNormal extends BasicAdmin
{
    use SelectPage;

    protected $model = 'CourseModel';

    /**
     * 课程管理
     */
    public function index(){
        $this->title = '课程管理';
        $this->_query($this->model)
            ->where('type',1)
            ->where(function ($db){
                if($this->request->has('status','get') && !empty($this->request->get('status'))){
                    $status = $this->request->get('status');
                    $db->where('status', $status);
                }
                if($this->request->has('cate_id','get') && !empty($this->request->get('cate_id'))){
                    $cate_id = $this->request->get('cate_id');
                    $db->where('cate_id', $cate_id);
                }
            })
            ->with(['coursecate'])
            ->page();
    }

    /**
     * 添加
     */
    public function add()
    {
        $this->title = '添加';
        return $this->_form($this->model, 'form');
    }

    public function _add_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $this->alterInfo($data);
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $this->title = '编辑';
        return $this->_form($this->model,'form');
    }

    public function _edit_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $this->alterInfo($data);
        }
    }

    protected function alterInfo(&$data){


        if(!isset($data['logo']) || empty($data['logo'])){
            $this->error('请上传课程图');
        }

        if(!isset($data['intro']) || empty($data['intro'])){
            $this->error('请上传详情图');
        }
        $data['type'] = 1;
    }

    /**
     * 删除
     */
    public function del()
    {
        $this->_delete($this->model);
    }

    /**
     * 启用/关闭
     */
    public function upstatus(){
        $this->_save($this->model, [
            'status' => $this->request->request('status'),
        ],'id', ['id' => $this->request->request('id')]);
    }

    public function upComment(){
        $this->_save($this->model, [
            'is_comment' => input('is_comment'),
        ],'id', ['id' => input('id')]);
    }

    /**
     * 导入
     */
    public function import()
    {
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/php-excel-reader/excel_reader2.php');
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/SpreadsheetReader.php');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error('未上传文件');
        }else {
            $upload = array(
                'uploadurl' => 'ajax/upload',
                'cdnurl'    => '',
                'savekey'   => '/upload/excel/{filemd5}{.suffix}',
                'maxsize'   => '1024mb',
                'mimetype'  => 'xls,xlsx',
                'multiple'  => false
            );

            preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
            $type = strtolower($matches[2]);
            $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
            $size = (int)$upload['maxsize'] * pow(999999, isset($typeDict[$type]) ? $typeDict[$type] : 0);
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';

            $mimetypeArr = explode(',', strtolower($upload['mimetype']));
            $typeArr = explode('/', $fileInfo['type']);

            //验证文件后缀
            if ($upload['mimetype'] !== '*' &&
                (
                    !in_array($suffix, $mimetypeArr)
                    || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
            ) {
                $this->error('只能上传xls,xlsx文件');
            }
            $replaceArr = [
                '{year}'     => date("Y"),
                '{mon}'      => date("m"),
                '{day}'      => date("d"),
                '{hour}'     => date("H"),
                '{min}'      => date("i"),
                '{sec}'      => date("s"),
                '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
                '{suffix}'   => $suffix,
                '{.suffix}'  => $suffix ? '.' . $suffix : '',
                '{filemd5}'  => md5_file($fileInfo['tmp_name']),
            ];
            $savekey = $upload['savekey'];
            $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

            $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
            $fileName = substr($savekey, strripos($savekey, '/') + 1);
            $splInfo = $file->move( '/www/wwwroot/huilife/public' . $uploadDir, $fileName);
            $file = '/www/wwwroot/huilife/public' . $uploadDir. $fileName;
            $Reader = new \SpreadsheetReader($file);
            foreach ($Reader as $Key => $Row) {
                if ($Key != 1 && !empty($Row)) {
                    $name = $Row[2]; //商品名
                    if ($name != '') {
                        //找到分类id
                        $cate_id = GoodsCateModel::where('name',$Row[1])->value('id',6);
                        $title = isset($Row[3])?$Row[3]:''; //标语
                        $market_price = isset($Row[4])?$Row[4]:''; //市场价
                        $price = isset($Row[5])?$Row[5]:''; //销售价
                        $unit = isset($Row[6])?$Row[6]:''; //单位
                        $stock = isset($Row[7])?$Row[7]:''; //库存
                        $poster_rate = isset($Row[8])?$Row[8]:''; //驿站长分成比例
                        $partner_rate = isset($Row[9])?$Row[9]:''; //合伙人分成比例
                        GoodsModel::create([
                            'cate_id'=>$cate_id,
                            'name'=>$name,
                            'title'=>$title,
                            'market_price'=>$market_price,
                            'price'=>$price,
                            'unit'=>$unit,
                            'stock'=>$stock,
                            'poster_rate'=>$poster_rate,
                            'partner_rate'=>$partner_rate,
                        ]);
                    }
                }
            }
            $this->success('导入成功，商品信息已更新！');
        }
    }

    /**
     * 导入模板
     */
    public function import_template()
    {
        $list[0] = [
            'id'=>'示例请删除',
            'cate_name'=>'米面粮油',
            'name'=>'柬埔寨香米',
            'title'=>'口感香甜 老少皆宜',
            'market_price'=>'10.00',
            'price'=>'9.90',
            'unit'=>'份',
            'stock'=>'999',
            'poster_rate'=>'2',
            'partner_rate'=>'1'
        ];
        $table_field = [
            ['A' ,'id', '序号'],
            ['B' ,'cate_name','分类'],
            ['C' ,'name', '商品名'],
            ['D' ,'title', '标语'],
            ['E' ,'market_price','市场价'],
            ['F' ,'price','销售价'],
            ['G' ,'unit','单位'],
            ['H' ,'stock','库存'],
            ['I' ,'poster_rate','驿站长分成比例'],
            ['J' ,'partner_rate','合伙人分成比例']
        ];
        return $this->_export($list, $table_field, '惠生活商品导入模板');
    }

}